<?php

namespace Beerus\Modules\Brand\Controllers;

use App\Admin\Extensions\Tools\UserButton;
use App\Http\Controllers\Controller;
use App\Pockets\GridDataModel as pGridDataModel;
use Biz\model\wiki\WikiBrandArea;
use Biz\model\wiki\WikiBrandAreaAd;
use Biz\model\wiki\WikiBrandAreaModule;
use Biz\tools\BizUrl;
use Doraemon\cache\Search\SpecialWord;
use Biz\model\brand\Brand as mBrand;
use Biz\service\brand\Brand as sBrand;
use Doraemon\tools\ImgUrl;
use Encore\Admin\Facades\Admin;
use Encore\Admin\Grid;
use Encore\Admin\Layout\Content;
use Encore\Admin\Widgets\Form;
use Encore\Admin\Widgets\Tab;
use Illuminate\Http\Request;
use Illuminate\Support\MessageBag;

/**
 * 品牌专区
 *
 * @category   Module name
 * @package    PSR
 * @subpackage Documentation\API
 * @author     zhouyang  <zhouyang@haohaozhu.com>
 * @license    GPL http://www.haohaozhu.com
 * @link       http://www.haohaozhu.com
 */

class BrandAreaController extends Controller
{
    public function index(Request $request, Content $content, $brand_id)
    {
        $tab = new Tab();
        $brandInfo = sBrand::getBrandInfoById($brand_id);
        $baseInfo = WikiBrandArea::admGetInfo($brand_id);
        $baseInfo['title'] = $brandInfo['brand_name'] ?? "";
        $baseInfo['keyword'] = $baseInfo['keyword'] ? $baseInfo['keyword'] : $baseInfo['title'];
        $baseInfo['share_title'] = strlen($baseInfo['share_title']) ? $baseInfo['share_title'] : vsprintf('「%s」品牌专区', [$baseInfo['title']]);
        $baseInfo['share_desc'] = strlen($baseInfo['share_desc']) ? $baseInfo['share_desc'] : vsprintf('快来看看住友家中的「%s」吧～', [$baseInfo['title']]);
        $baseInfo['share_pic_id'] = strlen($baseInfo['share_pic_id']) ? $baseInfo['share_pic_id'] : $brandInfo['logo'];

        //基础信息
        $form = new Form($baseInfo);
        $form->disableReset();
        $form->text('title', '品牌名称')->readonly();
        $form->text('keyword', '按此词汇抓取note及文章')->required();
        $form->textarea('search_key', '按此词汇抓取特型搜索词[逗号隔开]');
        $form->text('share_title', '分享标题');
        $form->text('share_desc', '分享描述');
        $form->imgUpload('share_pic_id', '分享图标', true, ['imgType' => ImgUrl::APPTYPE_BIZ, 'imgSize' => ImgUrl::IMAGE_SIZE_SQ_PHONE]);
        $form->radio('show_type', '展示控制')->options(WikiBrandArea::ADM_SHOW_TYPE_MAP)->default($baseInfo['show_type'] ?? WikiBrandArea::SHOW_TYPE_WHOLE);
        $form->imgUpload('bg_pic_id', '顶部背景');
        $form->text('pic_up', '置顶晒图');
        $form->text('pic_down', '隐藏晒图');
        $form->text('note_up', '置顶案例');
        $form->text('note_down', '隐藏案例');
        $form->action('/admin/brand/brandArea/' . $brand_id);

        //列表信息
        $gridModel = new pGridDataModel($moduleList = WikiBrandAreaModule::admModuleList($brand_id));
        $detailGrid = Admin::grid($gridModel,
            function (Grid $grid) {
                $grid->disableFilter();
                $grid->disableExport();
                $grid->disableCreateButton();
                $grid->disableRowSelector();
                $grid->disablePagination();
                //添加按钮
                $grid->tools(function (Grid\Tools $tool) {
                    $tool->prepend(new UserButton(UserButton::TYPE_HREF, 'addModule/' . WikiBrandAreaModule::MODULE_TYPE_TOPIC, '添加话题', 'fa-plus'));
                    $tool->prepend(new UserButton(UserButton::TYPE_HREF, 'addModule/' . WikiBrandAreaModule::MODULE_TYPE_TEST, '添加测评', 'fa-plus'));
                    $tool->prepend(new UserButton(UserButton::TYPE_HREF, 'addModule/' . WikiBrandAreaModule::MODULE_TYPE_H5, '添加H5', 'fa-plus'));
                });
                $grid->column('module_type_desc', '类型');
                $grid->column('title', '名称');
                $grid->column('link', '链接');
                $grid->column('unique_id', 'ID');
                $grid->column('sort', '权重');
                $grid->actions(function (Grid\Displayers\Actions $actions) {

                });
            });

        //广告位
        $adGridModel = new pGridDataModel($adList = WikiBrandAreaAd::admModuleList($brand_id));
        $adForm = new Form();
        $adForm->text('title', '广告名称')->required();
        $adForm->fieldChange('ad_type', '广告类型', $adForm)
            ->options(WikiBrandAreaAd::ADM_AD_TYPE_MAP)
            ->default(WikiBrandAreaAd::AD_TYPE_PIC)
            ->callableMap([
                WikiBrandAreaAd::AD_TYPE_PIC => function ($adForm) {
                    $adForm->imgUpload('img', 'banner图');
                    $adForm->linkSelect('link');
                },
                WikiBrandAreaAd::AD_TYPE_VIDEO => function ($adForm) {
                    $adForm->imgUpload('img', 'banner图');
                    $adForm->text('link', '视频链接');
                },
            ])
            ->required();
        $adForm->text('sort', '权重');
        $adForm->action('/admin/brand/brandArea/' . $brand_id . '/addAd/');

        $adGrid = Admin::grid($adGridModel,
            function (Grid $grid) {
                Admin::script($this->script($grid->tableID));

                $grid->disableFilter();
                $grid->disableExport();
                $grid->disableCreateButton();
                $grid->disableRowSelector();
                $grid->disablePagination();
                $grid->column('ad_type_desc', '广告类型');
                $grid->column('img_url', '图片')->image();
                $grid->column('title', '广告名称')->editable();
                $grid->column('link', '视频/图片链接')->display(function ($title, $column) {
                    if ($this->ad_type == WikiBrandAreaAd::AD_TYPE_PIC) {
                        return $column->linkSelect();
                    } else {
                        return $column->editable();
                    }
                });
                $grid->column('sort', '权重')->editable();
                $grid->actions(function (Grid\Displayers\Actions $actions) {
                    $actions->disableEdit();
                    $actions->append('<a href="javascript:void(0);" data-id="ad_' . $this->row->id . '" class="grid-row-delete">
    <i class="fa fa-trash"></i>
</a>');
                });
            });
        $tab->add('基础信息', $form);
        $tab->add('活动tab', $detailGrid->render(), $active = $request->input('active', false));
        $tab->add('广告位', $adForm->render() . $adGrid->render(), $active = $request->input('ad_active', false));
        return $content
            ->header('编辑品牌专区')
            ->description(' ')
            ->breadcrumb([
                'text' => '品牌管理',
                'url' => '/brand'
            ], ['text' => '编辑品牌专区'])
            ->row($tab);
    }

    private static function moduleForm($content, $brand_id, $module_type, $module_info = [])
    {
        $form = new Form($module_info);
        $form->hidden('id', '');
        $form->text('title', '名称');
        switch ($module_type) {
            case WikiBrandAreaModule::MODULE_TYPE_TOPIC:
                $form->text('unique_id', '话题ID');
                break;
            case WikiBrandAreaModule::MODULE_TYPE_TEST:
                $form->text('unique_id', '测评ID');
                break;
            case WikiBrandAreaModule::MODULE_TYPE_H5:
                $form->imgUpload('pic_id', '封面');
                $that = $form->text('link', 'H5链接');
                if ($module_info['h5_link']) {
                    $that->help('加密后的地址:' . $module_info['h5_link']);
                }
                break;
            default:
                throw new \Exception('未开发的模块');
                break;
        }
        $form->text('sort', '权重');
        $form->action('/admin/brand/brandArea/' . $brand_id . '/addModule/' . $module_type);
        $text = (empty($module_info) ? '添加' : '修改') . WikiBrandAreaModule::getTypeName($module_type);
        return $content
            ->header($text)
            ->description(' ')
            ->breadcrumb(
                [
                    'text' => '品牌管理',
                    'url' => '/brand'
                ],
                [
                    'text' => '编辑品牌专区',
                    'url' => '/brand/brandArea/' . $brand_id
                ],
                ['text' => $text])
            ->row($form);
    }

    public function editModule(Content $content, $brand_id, $module_id)
    {
        try {
            $module_info = WikiBrandAreaModule::admGetInfo($module_id);
            if (!$module_info) {
                throw new \Exception('模块不存在');
            }
            return self::moduleForm($content, $brand_id, $module_info['module_type'], $module_info);
        } catch (\Exception $e) {
            $error = new MessageBag([
                'title' => $e->getMessage()
            ]);
            return back()->with(compact('error'));
        }
    }

    public function modifyAd(Request $request, $brand_id, $module_id)
    {
        $pjax = false;
        $status = $request->input('status');
        $message = "修改成功";
        try {
            $name = $request->input('name', '');
            switch ($name) {
                case 'sort':
                    $data = [
                        'sort' => $request->input('value', '0'),
                    ];
                    break;
                case 'title':
                    $data = [
                        'title' => $request->input('value', ''),
                    ];
                    break;
                case 'link'://修改视频链接
                    $data = [
                        'link' => $request->input('value', ''),
                    ];
                    break;
                case ''://修改banner链接
                    $linkUrl = $request->input("link_url", '');
                    preg_match("/^hhz:\/\/./", $linkUrl, $re);
                    if ($re) {
                        $linkUrl = BizUrl::SCHEME_APP_BASE64 . '://' . base64_encode($linkUrl);
                    }
                    $outLink = $request->input("out_link", '');
                    $data = [
                        'link_type' => $request->input("link_type", ''),
                        'link_params' => $request->input("link_params") ? json_encode($request->input("link_params"), JSON_UNESCAPED_UNICODE) : $request->input("link_params"),
                    ];
                    break;
            }
            if (empty($data)) {
                throw new \Exception('没有修改的数据');
            }
            $id = WikiBrandAreaAd::admSaveInfo($module_id, $data);
            if (!$id) {
                throw new \Exception('保存失败');
            }
        } catch (\Exception $e) {
            $status = false;
            $message = $e->getMessage();
            if (!$pjax) {
                return response()->json(['errors' => [$message]], 422);
            }
        }
        return response()->json(compact('status', 'message'));
    }

    public function saveAd(Request $request, $brand_id)
    {
        try {
            $ad_type = $request->input('ad_type', WikiBrandAreaAd::AD_TYPE_VIDEO);
            $img = trim($request->input('img', ''));
            $link = trim($request->input('link', ''));
            $title = trim($request->input('title', ''));
            $sort = $request->input('sort', 0);
            $linkUrl = $request->input("link_url", '');
            preg_match("/^hhz:\/\/./", $linkUrl, $re);
            if ($re) {
                $linkUrl = BizUrl::SCHEME_APP_BASE64 . '://' . base64_encode($linkUrl);
            }
            $outLink = $request->input("out_link", '');
            $link_params = $request->input("link_params", []);
            $data = [
                'ad_type' => $ad_type,
                'brand_id' => $brand_id,
                'link' => $link,
                'img' => $img,
                'title' => $title,
                'sort' => intval($sort),
                'link_type' => $request->input("link_type", ''),
                'link_params' => json_encode($link_params, JSON_UNESCAPED_UNICODE),
            ];
            $id = WikiBrandAreaAd::admSaveInfo(0, $data);
            if (!$id) {
                throw new \Exception('保存失败');
            }
            $success = new MessageBag([
                'title' => '保存成功'
            ]);
            return redirect('/admin/brand/brandArea/' . $brand_id . '?ad_active=true')->with(compact('success'));
        } catch (\Exception $e) {
            $error = new MessageBag([
                'title' => $e->getMessage()
            ]);
            return back()->with(compact('error'));
        }
    }

    public function addModule(Content $content, $brand_id, $module_type)
    {
        return self::moduleForm($content, $brand_id, $module_type);
    }

    public function delModule($brand_id, $module_id)
    {
        try {
            $module_id = explode('_', $module_id);
            if (count($module_id) > 1) {
                $tab = $module_id[0];
                $module_id = $module_id[1];
                switch ($tab) {
                    case 'ad':
                        $module_info = WikiBrandAreaAd::admGetInfo($module_id);
                        if (!$module_info) {
                            throw new \Exception('模块不存在');
                        }
                        $id = WikiBrandAreaAd::admDelModule($module_id);
                        if (!$id) {
                            throw new \Exception('保存失败');
                        }
                        break;
                }
            } else {
                $module_info = WikiBrandAreaModule::admGetInfo($module_id);
                if (!$module_info) {
                    throw new \Exception('模块不存在');
                }
                $id = WikiBrandAreaModule::admDelModule($module_id);
                if (!$id) {
                    throw new \Exception('保存失败');
                }
            }

            return response()->json([
                'status' => true,
                'message' => "删除成功",
            ]);
        } catch (\Exception $e) {
            return response()->json([
                'status' => false,
                'message' => "操作失败," . $e->getMessage(),
            ]);
        }
    }

    public function script($id)
    {
        return <<<SCRIPT
        $("#$id").find('.grid-row-delete').each(function(){
            if ($(this).index() == 0) {
                $(this).hide();
            }
        });
SCRIPT;

    }
    /**
     * 保存模块信息
     * @param Request $request
     * @param $brand_id
     * @param $module_type
     * @return \Illuminate\Http\RedirectResponse
     */
    public function saveModule(Request $request, $brand_id, $module_type)
    {
        try {
            $module_id = $request->input('id', 0);
            $sort = $request->input('sort', 0);
            $unique_id = trim($request->input('unique_id', ''));
            $link = trim($request->input('link', ''));
            $data = [
                'title' => $request->input('title', ''),
                'brand_id' => $brand_id,
                'module_type' => $module_type,
                'sort' => $sort,
            ];
            switch ($module_type) {
                case WikiBrandAreaModule::MODULE_TYPE_TOPIC:
                    if (!strlen($unique_id)) {
                        throw new \Exception('请填写话题ID');
                    }
                    $data['unique_id'] = $unique_id;
                    break;
                case WikiBrandAreaModule::MODULE_TYPE_TEST:
                    if (!strlen($unique_id)) {
                        throw new \Exception('请填写测评ID');
                    }
                    $data['unique_id'] = $unique_id;
                    break;
                case WikiBrandAreaModule::MODULE_TYPE_H5:
                    if (!strlen($link)) {
                        throw new \Exception('请填写H5链接');
                    }
                    $data['link'] = $link;
                    $data['pic_id'] = $request->input('pic_id', '');
                    break;
                default:
                    throw new \Exception('未开发的模块');
                    break;
            }

            $id = WikiBrandAreaModule::admSaveInfo($module_id, $data);
            if (!$id) {
                throw new \Exception('保存失败');
            }
            $success = new MessageBag([
                'title' => '保存成功'
            ]);
            return redirect('/admin/brand/brandArea/' . $brand_id . '?active=true')->with(compact('success'));
        } catch (\Exception $e) {
            $error = new MessageBag([
                'title' => $e->getMessage()
            ]);
            return back()->with(compact('error'));
        }
    }

    /**
     * 保存基础信息
     * @param Request $request
     * @param $brand_id
     * @return \Illuminate\Http\RedirectResponse
     */
    public function saveBaseInfo(Request $request, $brand_id)
    {
        try {
            $data = [
                'show_type' => $request->input('show_type', WikiBrandArea::SHOW_TYPE_WHOLE),
                'share_title' => $request->input('share_title', ''),
                'share_desc' => $request->input('share_desc', ''),
                'share_pic_id' => $request->input('share_pic_id', ''),
                'bg_pic_id' => $request->input('bg_pic_id', ''),
                'pic_up' => $request->input('pic_up', ''),
                'pic_down' => $request->input('pic_down', ''),
                'note_up' => $request->input('note_up', ''),
                'note_down' => $request->input('note_down', ''),
                'keyword' => trim($request->input('keyword', '')),
                'search_key' => trim($request->input('search_key', '')),
            ];

            $id = WikiBrandArea::admSaveInfo($brand_id, $data);
            if (!$id) {
                throw new \Exception('保存失败');
            }

            //存缓存信息
            $brand = mBrand::getInfo($brand_id);
            if (!empty($data['search_key'])) {
                $data['search_key'] = str_replace('，', ',', trim(str_replace(' ', '', $data['search_key'])));
                $cacheData = SpecialWord::getCache(SpecialWord::_CACHE_BRAND);
                $exits = false;
                $exitsKeys = [];
                $exitsBrandId = 0;
                $searchKeys = explode(',', $data['search_key']);
                if (!empty($cacheData)) {
                    foreach ($cacheData as $_k => $_item) {
                        if (!empty($_item)) {
                            $_item = json_decode($_item, true);
                            if ($_item['brand_id'] != $brand_id) {
                                $exitArr = array_intersect($searchKeys, $_item['brand_tag']);
                                if ($exitArr) {
                                    $exitsKeys = implode(',', $exitArr);
                                    $exits = true;
                                    $exitsBrandId = $_item['brand_id'];
                                    break;
                                }
                            }
                        }
                    }
                }
                if ($exits) {
                    $exitsBrandName = '';
                    if ($exitsBrandId) {
                        $exitsBrandName = mBrand::getInfo($exitsBrandId);
                        $exitsBrandName = $exitsBrandName ? $exitsBrandName['brand_name'] : '';
                    }
                    throw new \Exception('特定搜索词「' . $exitsKeys . '」已经存在于品牌：' . $exitsBrandId . '「' . $exitsBrandName . '」中');
                }
                $cacheVal = explode(',', $brand['brand_name'] . ',' . $data['search_key']);
            } else {
                $cacheVal = [$brand['brand_name']];
            }
            $cacheData = [
                'brand_id' => $brand_id,
                'brand_tag' => $cacheVal
            ];
            if (isset($cacheData)) {
                SpecialWord::setZcache(
                    $brand_id,
                    SpecialWord::_CACHE_BRAND,
                    json_encode($cacheData, true)

                );
            }

            $success = new MessageBag([
                'title' => '保存成功'
            ]);
            return redirect('/admin/brand/brandArea/' . $brand_id)->with(compact('success'));
        } catch (\Exception $e) {
            $error = new MessageBag([
                'title' => $e->getMessage()
            ]);
            return back()->with(compact('error'));
        }
    }
}
